<%--
  Created by IntelliJ IDEA.
  User: 97506
  Date: 2019/6/4
  Time: 20:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <title>员工列表</title>
    <script src="${APP_PATH}/static/js/jquery-3.4.1.min.js"></script>

    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>

    <script type="text/javascript">
        var totalRecord, currentPage;
        $(function () {
            select_by_pagenum(1);
        });


        //加载result信息
        function build_table(result) {
            $("tbody").html("");
            result = JSON.parse(result);

            var list = result.extend.emps.list;
            $.each(list, function (index, item) {
                var check = $("<td><input type='checkbox' class='check_item'></td>")
                var empId = $("<td></td>").append(item.empId);
                var epmName = $("<td></td>").append(item.epmName);
                var gender = $("<td></td>").append(item.gender);
                var email = $("<td></td>").append(item.email);
                var deptName = $("<td></td>").append(item.department.deptName);

                var editBtn = $("<button></button>").attr("edit_id", item.empId).addClass("btn btn-warning btn-sm edit_btn")
                    .append($("<span></span>").addClass("glyphicon glyphicon-pencil").append("修改"));

                var deleteBtn = $("<button></button>").attr("delete_id", item.empId).addClass("btn btn-danger btn-sm delete_btn")
                    .append($("<span></span>").addClass("glyphicon glyphicon-remove").append("删除"));

                //将两个按钮用<th></th>标签包裹
                var btn = $("<th></th>").append(editBtn).append(" ").append(deleteBtn);

                //append方法执行完了之后返回之前的元素
                $("<tr></tr>").append(check)
                    .append(empId)
                    .append(epmName)
                    .append(gender)
                    .append(email)
                    .append(deptName)
                    .append(btn).appendTo("tbody");
            });
        }

        //构建页码信息
        function build_page_nav(result) {
            result = JSON.parse(result);
            var pageNum = result.extend.emps.pageNum;
            var pages = result.extend.emps.pages;
            var total = result.extend.emps.total;
            totalRecord = total;
            currentPage = pageNum;

            $("#page_nav").html("当前为<kbd>" + pageNum + "</kbd>页，总共<kbd>" + pages + "</kbd>页，总记录为<kbd>" + total + "</kbd>项");
        }

        //构建分页条
        function build_page_bar(result) {
            result = JSON.parse(result);
            var navigatepageNums = result.extend.emps.navigatepageNums;

            var pageBar = "<li onclick=\"select_by_pagenum(" + 1 + ")\"><a href=\"#\">首页</a></li>";

            if (result.extend.emps.hasPreviousPage == true) {
                pageBar += "<li onclick='select_by_pagenum(" + (result.extend.emps.pageNum - 1) + ")'>\n" +
                    "      <a href=\"#\" aria-label=\"Previous\">\n" +
                    "        <span aria-hidden=\"true\">&laquo;</span>\n" +
                    "      </a>\n" +
                    "    </li>";
            }

            $.each(navigatepageNums, function (index, item) {
                if (item == result.extend.emps.pageNum) {
                    pageBar += "<li class='active' onclick='select_by_pagenum(" + item + ")'><a href='#'>" + item + "</a></li>";
                } else {
                    pageBar += "<li onclick='select_by_pagenum(" + item + ")'><a href='#'>" + item + "</a></li>";
                }
            });

            if (result.extend.emps.hasNextPage == true) {
                pageBar += "<li onclick=\"select_by_pagenum(" + (result.extend.emps.pageNum + 1) + ")\">\n" +
                    "                            <a href=\"#\" aria-label=\"Next\">\n" +
                    "                                <span aria-hidden=\"true\">&raquo;</span>\n" +
                    "                            </a>\n" +
                    "                        </li>";
            }

            pageBar += "<li onclick=\"select_by_pagenum(" + result.extend.emps.pages + ")\"><a href=\"#\">尾页</a></li>";

            $(".pagination").html(pageBar);
        }

        function select_by_pagenum(pn) {
            $.ajax({
                url: "${APP_PATH}/emps",
                type: "GET",
                data: {pn: pn},
                success: function (result) {
                    build_table(result);
                    build_page_nav(result);
                    build_page_bar(result);
                }
            })
        }

    </script>
</head>
<body>
<!-- Modal 员工修改的模态框 -->
<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalUpdateLabel">修改员工信息</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal update">

                    <div class="form-group">
                        <label for="empName_inupt" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" name="epmName" class="form-control" id="empName_update"
                                   placeholder="empName" value="">
                            <span class="help-empName"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="email_inupt" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="email_update"
                                   placeholder="email@qq.com">
                            <span class="help-email"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="male_update" value="男" checked> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="famle_update" value="女"> 女
                            </label>
                        </div>

                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">department</label>
                        <div class="col-sm-5">
                            <select class="form-control" name="dId">

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="empt_update_btn">更新</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
<!-- Modal 员工添加的模态框 -->
<div class="modal fade" id="empModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">新增员工记录</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal save">

                    <div class="form-group">
                        <label for="empName_inupt" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="email" name="epmName" class="form-control" id="empName_inupt"
                                   placeholder="empName">
                            <span class="help-empName"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="email_inupt" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="email_inupt"
                                   placeholder="email@qq.com">
                            <span class="help-email"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="male" value="男" checked> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="famle" value="女"> 女
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">department</label>
                        <div class="col-sm-5">
                            <select class="form-control" name="dId">

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="empt_save_btn">保存</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
<!--搭建显示页面-->
<div class="container">
    <!--标题-->
    <div class="row">
        <div class="col-lg-12">
            <h1>员工信息管理系统</h1>
        </div>
    </div>
    <!--按钮-->
    <div class="row">
        <div class="col-lg-4 col-lg-offset-10">
            <button type="button" id="emp_add" class="btn btn-primary" data-toggle="modal" data-target="#empModal">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
            </button>
            <button type="button" class="btn btn-danger multi_delete">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
            </button>
        </div>
    </div>
    <!--显示表格数据-->
    <div class="row" style="margin-top: 20px">
        <div class="col-lg-12">
            <table class="table table-hover table-bordered">
                <thead>
                <tr>
                    <th><input type="checkbox" class="check_all"></th>
                    <th>#</th>
                    <th>empName</th>
                    <th>gender</th>
                    <th>email</th>
                    <th>deptName</th>
                    <th></th>
                </tr>
                </thead>

                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <!--分页-->
    <div class="row">
        <!--分页信息-->
        <div class="col-lg-6" id="page_nav">
            当前为<kbd></kbd>页，总共<kbd></kbd>页，总记录为<kbd></kbd>项。
        </div>

        <!--分页条-->
        <div class="col-md-6">
            <nav aria-label="Page navigation">
                <ul class="pagination">

                </ul>
            </nav>
        </div>
    </div>
</div>
<script>
    function form_reset(ele) {
        $(ele)[0].reset();
        $(ele).find("*").removeClass("has-success has-error result");
        $(ele).find(".help-email").text("");
        $(ele).find(".help-empName").text("");
        $("#empt_save_btn").removeAttr("disabled");
    }

    //启动模板页按钮事件
    $("#emp_add").on("click", function () {
        form_reset("#empModal form");
        getDepartments();
        show_validate_status("#empName_inupt", ".help-empName", null, "");
        show_validate_status("#email_inupt", ".help-email", null, "");
    });

    //得到所有的公寓信息
    function getDepartments() {
        $(".form-control").empty();
        $.ajax({
            type: "get",
            url: "${APP_PATH}/deps",
            success: function (result) {
                result = JSON.parse(result);
                deps = result.extend.deps;
                $.each(deps, function (index, item) {
                    $("<option></option>").attr("value", item.deptId).append(item.deptName).appendTo(".form-control");
                });
            }
        })
    }

    //得到所有的公寓信息
    $("#empt_save_btn").click(function () {
        if (!validate_form()) {
            return;
        }
        $.ajax({
            type: "POST",
            url: "${APP_PATH}/emps",
            data: $(".save").serialize(),
            success: function (result) {
                console.log(result);
                result = JSON.parse(result);
                alert("保存成功！");
                $("#empModal").modal('hide');
                select_by_pagenum(totalRecord);
            }
        });

    });

    function validate_form() {
        var validate_result = true;
        var empName = $("#empName_inupt").val();
        var email = $("#email_inupt").val();
        var gender = $("input[name='gender']:checked").val();
        var depart = $("select[name='dId']").val();
        console.log(empName + " " + email + " " + gender + " " + depart);
        if (!validate_empName(empName)) {
            validate_result = false;
            show_validate_status("#empName_inupt", ".help-empName", "has-error", "姓名支持2-5个字符的中文字符");
        } else {
            show_validate_status("#empName_inupt", ".help-empName", "has-success", "");
        }
        if (!validate_email(email)) {
            validate_result = false;
            show_validate_status("#email_inupt", ".help-email", "has-error", "邮箱格式输入错误");
        } else {
            show_validate_status("#email_inupt", ".help-email", "has-success", "");
        }
        if (validate_result) {
            show_validate_status("#empName_inupt", ".help-empName", "has-success", "");
            show_validate_status("#email_inupt", ".help-email", "has-success", "");
        }
        return validate_result;
    }

    function validate_empName(empName) {
        var regName = /^[\u4E00-\u9FA5]{1,6}$/;
        return regName.test(empName);
    }

    function validate_email(email) {
        var regEmail = /^[a-zA-Z0-9]\w+@\w+\.(com|cn|edu)$/;
        return regEmail.test(email);
    }

    function show_validate_status(ele, ele2, status, msg) {
        $(ele).parent().removeClass("has-success has-error");
        $(ele2).empty();
        if (status != null) {
            $(ele).parent().addClass(status);
            $(ele2).append(msg);
        }
    }

    $("#empName_inupt").change(function () {
        var empName = this.value;
        $.ajax({
            type: "post",
            url: "${APP_PATH}/checkuser",
            data: {empName: empName},
            success: function (result) {
                result = JSON.parse(result);
                if (result.code == 0) {
                    show_validate_status("#empName_inupt", ".help-empName", "has-error", "用户名已被占用!");
                    $("#empt_save_btn").attr("disabled", "");
                } else if (result.code == 100) {
                    show_validate_status("#empName_inupt", ".help-empName", "has-success", "用户名可以使用!");
                    $("#empt_save_btn").removeAttr("disabled");
                }
            }
        })
    });
    $(document).on("click", ".edit_btn", function () {

        $('#empUpdateModal').modal('show');
        getDepartments();
        $("#empName_update").attr("disabled", "disabled");
        //查找员工信息显示在模态框中
        getEmpById(this.getAttribute("edit_id"));
        $("#empt_update_btn").attr("edit_id", this.getAttribute("edit_id"));

    });

    $(document).on("click", ".delete_btn", function () {
        if (confirm("确认删除id为" + $(this).attr("delete_id") + "的信息吗?")) {
            $.ajax({
                type: "DELETE",
                url: "${APP_PATH}/emps/" + $(this).attr("delete_id"),
                success: function (result) {
                    alert("删除成功！");
                    select_by_pagenum(currentPage);
                }
            })
        }

    });

    function getEmpById(id) {
        $.ajax({
            url: "${APP_PATH}/emps/" + id,
            type: "get",
            success: function (result) {
                result = JSON.parse(result);
                var empName = result.extend.emp.epmName;
                var email = result.extend.emp.email;
                var gender = result.extend.emp.gender;
                var dep = result.extend.emp.dId;
                $("#empName_update").val(empName);
                $("#email_update").val(email);
                $("input[name=gender]").val([gender]);
                $("select[name=dId]").val([dep]);
            }
        })
    }

    //点击更新按钮
    $("#empt_update_btn").on("click", function () {
        $.ajax({
            type: "PUT",
            url: "${APP_PATH}/emps/" + $(this).attr("edit_id"),
            data: $(".update").serialize() + "&empId=" + $(this).attr("edit_id"),
            success: function (result) {
                alert("更新成功！");
                $("#empUpdateModal").modal('hide');
                select_by_pagenum(currentPage);
            }
        })
    });

    $(document).on("click", ".check_all", function () {
        $(".check_item").prop("checked", $(this).prop("checked"));
    });

    $(document).on("click", ".check_item", function () {
        if ($(".check_item:checked").length == $(".check_item").length) {
            $(".check_all").prop("checked", true);
        } else {
            $(".check_all").prop("checked", false);
        }
    });

    $(".multi_delete").on("click", function () {
        var ids = "";
        var ids_show = "";
        $.each($(".check_item:checked"), function () {
            ids += $(this).parent().next().text() + "-";
            ids_show += $(this).parent().next().text() + ",";
        });
        ids = ids.substring(0, ids.length - 1);
        ids_show = ids_show.substring(0, ids_show.length - 1);
        if (confirm("确认多项删除 id为：" + ids_show + "的信息吗？")) {
            $.ajax({
                url: "${APP_PATH}/emps/" + ids,
                type: "DELETE",
                success: function (result) {
                    alert("删除成功！");
                    $(".check_all").prop("checked", false);
                    select_by_pagenum(currentPage);
                }
            })
        }
    });


</script>
</body>
</html>
